package com.loveto.service;

import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.List;
import java.util.Random;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.graphics.drawable.AnimationDrawable;
import android.os.Bundle;
import android.os.Handler;
import android.text.Spannable;
import android.text.SpannableStringBuilder;
import android.text.style.ForegroundColorSpan;
import android.util.Log;
import android.view.Gravity;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.view.inputmethod.InputMethodManager;
import android.widget.EditText;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.LinearLayout.LayoutParams;

import com.loveto.common.ImageDownloader;
import com.loveto.common.JsonUtils;
import com.loveto.common.SoftKeyboardDetectorView;
import com.loveto.common.SoftKeyboardDetectorView.OnHiddenKeyboardListener;
import com.loveto.common.SoftKeyboardDetectorView.OnShownKeyboardListener;
import com.loveto.constant.LovetoConstant;
import com.loveto.constant.LovetoGiftAnims;
import com.loveto.model.GiftInfo;

public class JoinTournamentMainActivity extends BaseActivity implements
View.OnClickListener{
	private static final int MIN_ANSWER_SIZE = 3;
	private static final int FIRST_ROUND = 1;
	private static final int SECOND_ROUND = 2;
	private static final int FINAL_ROUND = 3;
	private static final int DIALOG_GIFT_EXPLAIN = 1;
	
	private ProgressDialog progressDialog;
	private String tournamentId;
	private String tournamentMakerID;
	private String roundAnswer;
	private String category;
	private String question;
	private int roundseq;
	private ImageView round1ImageView;
	private ImageView round2ImageView;
	private ImageView round3ImageView;
	private EditText editTextAnswer;
	private LinearLayout questionLayer;
	private ImageView nextRoundBtn;
	private Dialog customDialogInstance;
	private boolean isJoinFinish = false;
	private String suspend_date;
	private String suspend_reason;
	private int groupnum;
	private String errorMsg;
	
	private String round1Answer = null;
	private String round2Answer = null;
	private String round3Answer = null;
	
	private String memberid = "";
	private String phone_uid = "";
	private Handler myHandler = new Handler();
	
	private int pointOriginal;
	private int pointChanged;
	private int giftID;
	private int joinOverPrice;
	private boolean isGiftPurchased;
	private String giftCharmText;
	private String giftPriceText;
	private String giftNameText;
	private List<AnimationDrawable> giftAnimList;
	private List<RelativeLayout> giftLayoutList;
	private List<GiftInfo> giftInfoList;
	private LinearLayout giftLayoutInner;
	private RelativeLayout selectedGiftLayout;
	private LovetoGiftAnims giftAnims = new LovetoGiftAnims();
	private DecimalFormat df = new DecimalFormat("#,##0");
	
	Animation slide;
	
	boolean isShowKeyboard;
	private SoftKeyboardDetectorView softKeyboardDetector; 
	
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.loveto_join_tournament_main);
		
		
		//초기화
		SharedPreferences pref = getSharedPreferences("userInfo", Activity.MODE_PRIVATE);
		memberid = pref.getString("memberid", "");
		phone_uid = pref.getString("phone_uid", "");
		pointOriginal = pref.getInt("point", 0);
		
		progressDialog = new ProgressDialog(this);
		round1ImageView = (ImageView)findViewById(R.id.round1Image);
		round2ImageView = (ImageView)findViewById(R.id.round2Image);
		round3ImageView = (ImageView)findViewById(R.id.round3Image);
		editTextAnswer = (EditText)findViewById(R.id.editTextAnswer);
		nextRoundBtn = (ImageView)findViewById(R.id.nextRound);
		questionLayer = (LinearLayout)findViewById(R.id.questionLayer);
		slide = AnimationUtils.loadAnimation(this, R.anim.join_tournament_slide);
		
		
		//전 엑티비티에서 토너먼트 번호 받아오기
		Intent intent = getIntent();
		tournamentId = intent.getStringExtra("tournamentID");
		tournamentMakerID = intent.getStringExtra("tournamentMakerID");
		joinOverPrice = intent.getIntExtra("joinOverPrice", 0); //받은 값이 0보다 크면 참여횟수 초과에 의해 코인을 소모하는 것을 의미 (참여 완료 시 DB에 적용해야 함)
		Log.d("tag","pointOriginal: " + pointOriginal + "joinOverPrice: " + joinOverPrice);
		pointOriginal = pointOriginal - joinOverPrice; //일단 코인이 줄어든 것으로 표시 (DB 적용은 참여 완료 시에)
		
		//클릭 리스너 달기
		nextRoundBtn.setOnClickListener(this);
		round1ImageView.setOnClickListener(this);
		round2ImageView.setOnClickListener(this);
		round3ImageView.setOnClickListener(this);
		((RelativeLayout)findViewById(R.id.btn_goto_back)).setOnClickListener(this);
		((ImageView)findViewById(R.id.btn_chargn_point)).setOnClickListener(this);
		((ImageView)findViewById(R.id.btn_explain_gift)).setOnClickListener(this);
				
		roundseq = FIRST_ROUND;
		
		if (isNetworkAvailableAndNotice()) {
			setRoundInfo();
			getGiftInfo();
		}
		
		giftAnimList = new ArrayList<AnimationDrawable>();
		giftLayoutList = new ArrayList<RelativeLayout>();
		giftInfoList = new ArrayList<GiftInfo>();
		//내 코인 숫자 초기화
		((TextView)findViewById(R.id.mycoin_text)).setText(df.format((double)pointOriginal));
		
		//키보드가 나왔는지 학인 처리 , AndroidManifest.xml에서 android:windowSoftInputMode 가 adjustResize 속성일 때만 가능.
		isShowKeyboard = false; //키보드 상태를 파악하기 위한
		softKeyboardDetector = new  SoftKeyboardDetectorView(this); //키보드가 나왔는지 확인하기 위한
		addContentView(softKeyboardDetector, new FrameLayout.LayoutParams(-1, -1));
		softKeyboardDetector.setOnShownKeyboard(new OnShownKeyboardListener() {
			@Override
			public void onShowSoftKeyboard() {
				isShowKeyboard = true;
				EditText editTextAnswer = (EditText) findViewById(R.id.editTextAnswer);
				editTextAnswer.setCursorVisible(true);
				Log.d("tag", "키보드가 떴습니당~");
			}
		});
		softKeyboardDetector.setOnHiddenKeyboard(new OnHiddenKeyboardListener() {
			
			@Override
			public void onHiddenSoftKeyboard() {
				EditText editTextAnswer = (EditText) findViewById(R.id.editTextAnswer);
				editTextAnswer.setCursorVisible(false);
				Log.d("tag", "키보드가 내려갔습니당~");
			}
		});
		
		
	}
	
	
	@Override
	public void onClick(View v) {
		switch (v.getId()) {
			case R.id.nextRound:
				Log.d("tag", "nextRound Button clicked!");
				hideKeyboard();
				switch(roundseq) {
					case FIRST_ROUND:
						round1Answer = editTextAnswer.getText().toString();
						if (checkRoundAnswer(FIRST_ROUND)) {
							roundseq++;
							round1ImageView.setImageResource(R.drawable.img_roundstep_1round_unselected);
							round2ImageView.setImageResource(R.drawable.img_roundstep_2round_selected);
							questionLayer.startAnimation(slide);
							setRoundInfo();
						} else {
							viewToast(Gravity.CENTER, 0, 0, "답변은 " + MIN_ANSWER_SIZE + "자 이상으로 입력해주세요.");
						}
						break;
					case SECOND_ROUND:
						round2Answer = editTextAnswer.getText().toString();
						if (checkRoundAnswer(SECOND_ROUND)) {
							roundseq++;
							round2ImageView.setImageResource(R.drawable.img_roundstep_2round_unselected);
							round3ImageView.setImageResource(R.drawable.img_roundstep_3round_selected);
							
							((ImageView)v).setImageResource(R.drawable.text_info_tournament_join);
							questionLayer.startAnimation(slide);
							setRoundInfo();
						} else {
							viewToast(Gravity.CENTER, 0, 0, "답변은 " + MIN_ANSWER_SIZE + "자 이상으로 입력해주세요.");
						}
						break;
					case FINAL_ROUND:
						round3Answer = editTextAnswer.getText().toString();
						if (checkRoundAnswer(FINAL_ROUND)) {
							// 1,2 ROUND를 거쳤는지 체크
							if (checkRoundAnswer(FIRST_ROUND) && checkRoundAnswer(SECOND_ROUND)) {
								// 서버에 답변정보 저장 및 참여완료 처리
								if (isNetworkAvailableAndNotice()) {
									saveTournamentJoinInfoToServer();
								}
								// 토너먼트 정보화면으로 이동
								//Intent intentMoveToPage = new Intent(this, InfoTournamentActivity.class);
								//intentMoveToPage.putExtra("tournamentID", tournamentId);
								//startActivity(intentMoveToPage);
							} else {
								viewToast(Gravity.CENTER, 0, 0, "답변 글자가" + MIN_ANSWER_SIZE + "자 미만인 ROUND가 있습니다.");
							}
						} else {
							viewToast(Gravity.CENTER, 0, 0, "답변은 " + MIN_ANSWER_SIZE + "자 이상으로 입력해주세요.");
						}
				}
				break;
			case R.id.round1Image:
				roundseq = FIRST_ROUND;
				round1ImageView.setImageResource(R.drawable.img_roundstep_1round_selected);
				round2ImageView.setImageResource(R.drawable.img_roundstep_2round_unselected);
				round3ImageView.setImageResource(R.drawable.img_roundstep_3round_unselected);
				nextRoundBtn.setImageResource(R.drawable.text_join_tournament_btn);
				questionLayer.startAnimation(slide);
				setRoundInfo();
				break;
			case R.id.round2Image:
				roundseq = SECOND_ROUND;
				round1ImageView.setImageResource(R.drawable.img_roundstep_1round_unselected);
				round2ImageView.setImageResource(R.drawable.img_roundstep_2round_selected);
				round3ImageView.setImageResource(R.drawable.img_roundstep_3round_unselected);
				nextRoundBtn.setImageResource(R.drawable.text_join_tournament_btn);
				questionLayer.startAnimation(slide);
				setRoundInfo();
				break;
			case R.id.round3Image:
				roundseq = FINAL_ROUND;
				round1ImageView.setImageResource(R.drawable.img_roundstep_1round_unselected);
				round2ImageView.setImageResource(R.drawable.img_roundstep_2round_unselected);
				round3ImageView.setImageResource(R.drawable.img_roundstep_3round_selected);
				nextRoundBtn.setImageResource(R.drawable.text_info_tournament_join);
				questionLayer.startAnimation(slide);
				setRoundInfo();
				break;
			case R.id.area_gift_item:
				Log.d("tag","띄우자1");
				giftID = Integer.parseInt(((TextView)v.findViewById(R.id.text_giftID)).getText().toString());
				giftCharmText = ((TextView)v.findViewById(R.id.text_point)).getText().toString();
				giftNameText = ((TextView)v.findViewById(R.id.text_gift_name)).getText().toString();
				giftPriceText = ((TextView)v.findViewById(R.id.text_price)).getText().toString();
				selectedGiftLayout = (RelativeLayout)v;
				Random oRandom = new Random();
				showDialog(3+(oRandom.nextInt(1000000)));//새로운 값을 넘겨야 팝업이 갱신되며, 같은 숫자가 갈 경우 가끔 버튼 갱신이 잘 안됨.
				break;
			case R.id.btn_explain_gift:
				Log.d("tag","띄우자1");
				showDialog(DIALOG_GIFT_EXPLAIN);//새로운 값을 넘겨야 팝업이 갱신되며, 같은 숫자가 갈 경우 가끔 버튼 갱신이 잘 안됨.
				break;
			case R.id.btn_chargn_point:
				Intent intentMoveToPage = new Intent(JoinTournamentMainActivity.this,ChargePointTStoreActivity.class);
				startActivity(intentMoveToPage);
				break;
			case R.id.btn_goto_back:
				finish();
				break;
			default:
				break;
		}
	}
	
/*	@Override
	public boolean dispatchTouchEvent(MotionEvent ev) {

	    switch (ev.getAction()){
	        case MotionEvent.ACTION_DOWN:
	        	EditText editTextAnswer = (EditText) findViewById(R.id.editTextAnswer);
	        	InputMethodManager mgr = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
	        	mgr.hideSoftInputFromWindow(editTextAnswer.getWindowToken(), 0);
	            break;
	        case MotionEvent.ACTION_UP:
	            break;
	    }

	    return super.dispatchTouchEvent(ev);
	}*/
	
	private void setRoundInfo() {
		Runnable runnable = new Runnable(){
			@Override
			public void run() {
				try {
					Log.d("tag", "setRoundInfo() start");
					String jsonText = JsonUtils.getStringFromUrl(LovetoConstant.ROUND_INFO_URL + "?tournamentid=" + tournamentId + "&roundseq=" + roundseq);
					//Log.d("tag", "jsonText : " + jsonText);
					try {
						JSONArray jsonArray = new JSONArray(jsonText);
						JSONObject object = jsonArray.getJSONObject(0);
						roundAnswer = getRoundAnswer(roundseq);
						Log.d("tag", "roundseq : " + roundseq);
						category = object.getString("question_low_category");
						Log.d("tag", "category : " + category);
						if (category.equals("null")) {
							category = "직접질문";
						}
						question = object.getString("question_content");
					} catch (JSONException e) {
						e.printStackTrace();
						Log.d("tag", "setRoundInfo() error, " + e.getMessage());
					}
				} catch (UnsupportedEncodingException e) {
					e.printStackTrace();
					Log.d("tag", "setRoundInfo() error, " + e.getMessage());
				} finally {
					//화면 갱신
					myHandler.post(new Runnable() {
						@Override
						public void run() {
							TextView questionCategory = (TextView)findViewById(R.id.question_category);
							TextView questionContent = (TextView)findViewById(R.id.question_content);
							if (roundAnswer!=null) {
								Log.d("tag", "roundAnswer : " + roundAnswer);
								editTextAnswer.setText(roundAnswer);
							} else {
								editTextAnswer.setText("");
							}
							questionCategory.setText("[" + category + "]");
							questionContent.setText(question);
							Log.d("tag", "setRoundInfo() end");
						}
					
					});
				}
			}
		};
		new Thread(runnable).start();
	}
	
	private void saveTournamentJoinInfoToServer() {
		progressDialog.setMessage("정보를 서버에 저장하고 있습니다.");
		progressDialog.show();
		Log.d("tag", "setRoundInfo() start");
		try {
			StringBuffer url = new StringBuffer(LovetoConstant.JOIN_TOURNAMENT_URL);
			url.append("?tournamentid=").append(tournamentId).append("&memberid=").append(memberid);
			url.append("&oneRoundAnswer=").append(URLEncoder.encode(round1Answer,"UTF-8")).append("&twoRoundAnswer=").append(URLEncoder.encode(round2Answer,"UTF-8")).append("&threeRoundAnswer=").append(URLEncoder.encode(round3Answer,"UTF-8"));
			url.append("&phone_uid=").append(phone_uid);
			if (isGiftPurchased) {
				url.append("&giftID=").append(giftID);
			}
			String jsonText = JsonUtils.getStringFromUrl(url.toString());
			Log.d("tag", "jsonText : " + jsonText);
			JSONObject object = new JSONObject(jsonText);
			String result = object.getString("result");
			String err = object.getString("err");
			String purchaseResult = object.getString("purchaseResult");
			String purchaseError = object.getString("purchaseError");
			int updatedPoint = object.getInt("updatedPoint");
			suspend_date = object.getString("suspend_date");
			suspend_reason = object.getString("suspend_reason");
			groupnum = object.getInt("groupnum");
			Log.d("tag", "result : " + result);
			Log.d("tag", "err : " + err);
			Log.d("tag", "purchaseResult : " + purchaseResult);
			Log.d("tag", "purchaseError : " + purchaseError);
			Log.d("tag", "updatedPoint : " + updatedPoint);
			Log.d("tag", "groupnum : " + groupnum);
			if (!"F".equals(result)) {
				isJoinFinish = true;
			}  else {
				errorMsg = err;
			}
			//로컬에 수정 된 최종 포인트 저장
			if (!"F".equals(result) && !"DB update error.".equals(purchaseError)) {
				SharedPreferences pref = getSharedPreferences("userInfo", Activity.MODE_PRIVATE);
				Editor editor = pref.edit();
				editor.putInt("point", updatedPoint);
				editor.commit();
			}
		} catch (JSONException e) {
			e.printStackTrace();
			Log.d("tag", "setRoundInfo() error, " + e.getMessage());
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
			Log.d("tag", "setRoundInfo() error, " + e.getMessage());
		} finally {
			if (isJoinFinish) {
				Intent intentMoveToPage = new Intent(JoinTournamentMainActivity.this,JoinTournamentCompleteActivity.class);
				intentMoveToPage.putExtra("groupnum", groupnum);
				intentMoveToPage.putExtra("tournamentId", tournamentId);
				intentMoveToPage.putExtra("round1Answer", round1Answer);
				finish();
				startActivity(intentMoveToPage);
			} else if ("Incorrect PhoneID".equals(errorMsg)){
				//폰 인증정보가 틀린 경우
				showAlertIncorrectPhoneID(JoinTournamentMainActivity.this);
			} else if ("SuspendedID".equals(errorMsg)) {
				//이용 정지 상태인 경우
				showAlertSuspendID(JoinTournamentMainActivity.this, suspend_date, suspend_reason);
			} else {
				showSimpleAlert("데이터 저장에 실패했습니다. 다시 시도해주세요.");
			}
		}
		progressDialog.dismiss();
		Log.d("tag", "setRoundInfo() end");
	}
	
	private boolean checkRoundAnswer(int roundseq) {
		boolean isAnswer = false;
		switch(roundseq) {
			case FIRST_ROUND:
				if (round1Answer != null && round1Answer.length() >= MIN_ANSWER_SIZE) {
					isAnswer = true;
				}
				break;
			case SECOND_ROUND:
				if (round2Answer != null && round2Answer.length() >= MIN_ANSWER_SIZE) {
					isAnswer = true;
				}
				break;
			case FINAL_ROUND:
				if (round3Answer != null && round3Answer.length() >= MIN_ANSWER_SIZE) {
					isAnswer = true;
				}
				break; 
			default: 
				break;
		}
		return isAnswer;
	}
	
	private String getRoundAnswer(int roundseq) {
		String answer = "";
		switch(roundseq) {
			case FIRST_ROUND:
				answer = round1Answer;
				break;
			case SECOND_ROUND:
				answer = round2Answer;
				break;
			case FINAL_ROUND:
				answer = round3Answer;
				break;
			default:
				break;
		}
		return answer;
	}
	
	private void getGiftInfo() {
		
		progressDialog.setMessage("정보를 불러오고있습니다.");
		progressDialog.show();
		
		giftLayoutInner = new LinearLayout(JoinTournamentMainActivity.this);
		giftLayoutInner.setLayoutParams(new LayoutParams(LayoutParams.FILL_PARENT, LayoutParams.WRAP_CONTENT));
		giftLayoutInner.setOrientation(LinearLayout.HORIZONTAL);
		
		Runnable runnable = new Runnable(){
			@Override
			public void run() {
				//UI 를 건들기 때문에 핸들러 사용.
				try {
					Log.d("tag", "getGiftInfo() start");
					String jsonText = JsonUtils.getStringFromUrl(LovetoConstant.GIFT_LIST);
					//Log.d("tag", "jsonText : " + jsonText);
					try {
						JSONArray jsonArray = new JSONArray(jsonText);
						for (int i = 0; i < jsonArray.length();i++) {
							JSONObject object = jsonArray.getJSONObject(i);
							GiftInfo giftInfo = new GiftInfo(object.getInt("giftid"), object.getString("category"), object.getString("category_kor"), object.getString("size"), object.getString("name"), object.getInt("price"), object.getInt("ability"), object.getString("regdate"));
							giftInfoList.add(giftInfo);
							makeGiftLayout(giftInfo);
						}
					} catch (JSONException e) {
						e.printStackTrace();
						Log.d("tag", "getGiftInfo() error, " + e.getMessage());
					}
				} catch (UnsupportedEncodingException e) {
					e.printStackTrace();
					Log.d("tag", "getGiftInfo() error, " + e.getMessage());
				} finally {
					//화면 갱신
					myHandler.post(new Runnable() {
						@Override
						public void run() {
							for (int i=0;i < giftInfoList.size();i++) {
								//
								//그림에 애니메이션을 넣을지 그림을 넣을지 판단
								int giftid = giftInfoList.get(i).getGiftid();
								ImageView image = (ImageView)giftLayoutList.get(i).findViewById(R.id.gift_img);
								if (giftAnims.getGiftAnimMap().containsKey(giftid)) { 
									//로컬에 선물 아이디에 대한 애니메이션 리소스가 있으면
									image.setBackgroundResource(giftAnims.getGiftAnimMap().get(giftid)); //애니메이션 지정
									giftAnimList.add((AnimationDrawable)image.getBackground()); //애니메이션 배열에 추가 (나중에 한번에 start 하기 위해)
								} else {
									//현재 버전에 선물에 대한 애니메이션 리소스가 없으면 FTP 의 1장짜리 이미지로 대체함
									String url = LovetoConstant.GIFT_IMAGE_URL + giftid + ".png";
									Log.d("tag","선물 url: " + url);
									ImageDownloader imageDownloader = new ImageDownloader();
									imageDownloader.download(url, image);
								}
							}
							//선물 레이아웃 한방에 넣기
							LinearLayout v_giftlist = (LinearLayout) findViewById(R.id.area_gift_list);
							v_giftlist.addView(giftLayoutInner);
							progressDialog.dismiss();
						}
					});
				}
			}
		};
		new Thread(runnable).start();
	}


	private void makeGiftLayout(GiftInfo giftInfo) {
		
		//값 받아오기
		int giftid = giftInfo.getGiftid();
		String category = giftInfo.getCategory();
		String size = giftInfo.getSize();
		int price = giftInfo.getPrice();
		String name = giftInfo.getName();
		
		//그림 넣을 위치
		
		RelativeLayout v_area_gift;
		if ("L".equals(size)) {
			v_area_gift = (RelativeLayout) getLayoutInflater().inflate(R.layout.loveto_gift_list_large, null);
		} else if ("M".equals(size)) {
			v_area_gift = (RelativeLayout) getLayoutInflater().inflate(R.layout.loveto_gift_list_medium, null);
		} else {
			v_area_gift = (RelativeLayout) getLayoutInflater().inflate(R.layout.loveto_gift_list_small, null);
		}
		
		//가격 넣기
		((TextView)v_area_gift.findViewById(R.id.text_price)).setText(""+price);
		//매력 포인트 넣기
		if ("innocent".equals(category)) {
			((TextView)v_area_gift.findViewById(R.id.text_point)).setText("청순 +" + (price/5));
		} else if ("sexy".equals(category)) {
			((TextView)v_area_gift.findViewById(R.id.text_point)).setText("섹시 +" + (price/5));
		} else if ("cuty".equals(category)) {
			((TextView)v_area_gift.findViewById(R.id.text_point)).setText("귀염 +" + (price/5));
		} else if ("intelligent".equals(category)) {
			((TextView)v_area_gift.findViewById(R.id.text_point)).setText("지적 +" + (price/5));
		}
		//선물ID 달기
		((TextView)v_area_gift.findViewById(R.id.text_giftID)).setText("" + giftid);
		//선물이름 달기
		((TextView)v_area_gift.findViewById(R.id.text_gift_name)).setText(name);
		
		//클릭 리스너 달기
		((RelativeLayout)v_area_gift.findViewById(R.id.area_gift_item)).setOnClickListener(this);
		giftLayoutList.add((RelativeLayout)v_area_gift.findViewById(R.id.area_gift_item)); //나중에 배경 초기화 하기 위한
		
		//선물 뷰에 추가하기
		giftLayoutInner.addView(v_area_gift);
	}
	
	//애니메이션은 윈도우에 포커스가 간 뒤에 스타트 시켜야 제대로 나옴.
	@Override
	public void onWindowFocusChanged(boolean hasFocus) {
		
		for (int i=0;i<giftAnimList.size();i++) {
			giftAnimList.get(i).start();
		}
		
	    super.onWindowFocusChanged(hasFocus);
	}
	
    @Override
    protected Dialog onCreateDialog(int id) {
        Dialog dialog;
        if (DIALOG_GIFT_EXPLAIN == id) {
        	dialog = getDialogExplainGift();
        } else {
        	Log.d("tag","선물 구매 다이얼로그 띄우기"); //새로운 인수값이 넘어와야 팝업이 갱신 되기 때문에 일단 난수 발생으로 처리함.
        	dialog = getDialogSelectGift();
        }
    	customDialogInstance = dialog;
        return dialog;
    }
	
    private Dialog getDialogSelectGift() {
        AlertDialog.Builder builder;
        AlertDialog alertDialog;
        
        //팝업 레이아웃 설정
   	 	LinearLayout layout = (LinearLayout) getLayoutInflater().inflate(R.layout.loveto_dialog_gift_selected, null);
   	 	//팝업 설명글 수정
   	 	((TextView)layout.findViewById(R.id.text_explain)).setText("선물은 주최자 ");
   	 	SpannableStringBuilder sp = new SpannableStringBuilder(tournamentMakerID);
   	 	sp.setSpan(new ForegroundColorSpan(getResources().getColor(R.color.textOrange)), 0, sp.length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
   	 	((TextView)layout.findViewById(R.id.text_explain)).append(sp);
   	 	sp = new SpannableStringBuilder("님의 매력포인트를 높여주는 효과가 있습니다. ");
   	 	((TextView)layout.findViewById(R.id.text_explain)).append(sp);
   	 	sp = new SpannableStringBuilder(tournamentMakerID);
   	 	sp.setSpan(new ForegroundColorSpan(getResources().getColor(R.color.textOrange)), 0, sp.length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
   	 	((TextView)layout.findViewById(R.id.text_explain)).append(sp);
   	 	sp = new SpannableStringBuilder("님의 매력에 어울리는 선물을 해보세요!");
   	 	((TextView)layout.findViewById(R.id.text_explain)).append(sp);
   	 	
   	 	sp = new SpannableStringBuilder("80%의 클로버");
   	 	sp.setSpan(new ForegroundColorSpan(getResources().getColor(R.color.textGreen)), 0, sp.length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
   	 	((TextView)layout.findViewById(R.id.text_explain_02)).append(sp);
   	 	sp = new SpannableStringBuilder("를 되돌려받을 수 있습니다.");
   	 	((TextView)layout.findViewById(R.id.text_explain_02)).append(sp);
   	 	
   	 	//팝업 선물 정조 표시
   	 	((TextView)layout.findViewById(R.id.popup_gift_name)).setText(giftNameText);
   	 	((TextView)layout.findViewById(R.id.popup_gift_price)).setText( giftPriceText);
   	 	((TextView)layout.findViewById(R.id.popup_gift_charm)).setText(giftCharmText);
   	 	//구매 확인 글 및 버튼 텍스트 수정
   	 	if (isGiftPurchased) {
   	 		((TextView)layout.findViewById(R.id.text_purchase_ask)).setText("선택하신 선물로 구매를 변경하시겠습니까?");
   	 		((ImageView)layout.findViewById(R.id.btn_ok_text)).setImageResource(R.drawable.text_change);
   	 	}
   	 	
   	 	//팝업 선물 이미지
   	 	ImageView image = (ImageView)layout.findViewById(R.id.img_gift);
   	 	Log.d("tag","선물 이미지 띄우기: " + giftID);
		if (giftAnims.getGiftImageMap().containsKey(giftID)) {
			//Log.d("tag","가져와보자");
			//로컬에 선물 아이디에 대한 이미지 리소스가 있으면
			image.setImageResource(giftAnims.getGiftImageMap().get(giftID)); //애니메이션 지정
		} else {
			//현재 버전에 선물에 대한 이미지 리소스가 없으면 FTP 의 1장짜리 이미지로 대체함
			String url = LovetoConstant.GIFT_IMAGE_URL + giftID + ".png";
			//Log.d("tag","선물 url: " + url);
			ImageDownloader imageDownloader = new ImageDownloader();
			imageDownloader.download(url, image);
		}
   	 	
		RelativeLayout okButton = (RelativeLayout)layout.findViewById(R.id.btn_ok);
        okButton.setOnClickListener(new OnClickListener() {
            //구매 버튼 처리
            @Override
            public void onClick(View v) {
            	int priceOfGift = Integer.parseInt(giftPriceText);
            	//보유한 돈이 부족하면 구매 불가.
            	if (pointOriginal < priceOfGift) {
            		customDialogInstance.dismiss();
            		showSimpleAlert("보유한 클로버가 부족합니다. 화면 하단의 '충전하기'를 통해 충전해주세요!");
            		return;
            	} else {
            		isGiftPurchased = true; //구매 했음.
            		//구매한 선물 이미지 화면에 표시
            		ImageView image = (ImageView) findViewById(R.id.purchased_gift_image);
            		//image.setBackgroundResource(R.drawable.bg_gift_background_blank);
            		if (giftAnims.getGiftImageMap().containsKey(giftID)) {
            			//로컬에 선물 아이디에 대한 이미지 리소스가 있으면
            			image.setImageResource(giftAnims.getGiftImageMap().get(giftID)); //애니메이션 지정
            		} else {
            			//현재 버전에 선물에 대한 이미지 리소스가 없으면 FTP 의 1장짜리 이미지로 대체함
            			String url = LovetoConstant.GIFT_IMAGE_URL + giftID + ".png";
            			ImageDownloader imageDownloader = new ImageDownloader();
            			imageDownloader.download(url, image);
            		}
            		//선물 목록에서 선택으로 변경
            		giftLayoutListReset();
            		//내 코인 액수 수정
            		pointChanged = pointOriginal - Integer.parseInt(giftPriceText);
            		((TextView)findViewById(R.id.mycoin_text)).setText(df.format((double)pointChanged));
            		customDialogInstance.dismiss();
            	}
            }
        });
        
        RelativeLayout cancelButton = (RelativeLayout)layout.findViewById(R.id.btn_cancel);
        cancelButton.setOnClickListener(new OnClickListener() {
        	//구매 취소 버튼 처리
            @Override
            public void onClick(View v) {
                customDialogInstance.dismiss();                
            }
        });
        
        builder = new AlertDialog.Builder(this);
        builder.setView(layout);
        alertDialog = builder.create();
                
        return alertDialog;
    }
    
    private Dialog getDialogExplainGift() {
    	AlertDialog.Builder builder;
    	AlertDialog alertDialog;
    	
    	//팝업 레이아웃 설정
    	LinearLayout layout = (LinearLayout) getLayoutInflater().inflate(R.layout.loveto_dialog_gift_explain, null);
    	//팝업 설명글 수정
    	((TextView)layout.findViewById(R.id.text_explain)).setText("선물은 주최자 ");
    	SpannableStringBuilder sp = new SpannableStringBuilder(tournamentMakerID);
    	sp.setSpan(new ForegroundColorSpan(getResources().getColor(R.color.textOrange)), 0, sp.length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
    	((TextView)layout.findViewById(R.id.text_explain)).append(sp);
    	sp = new SpannableStringBuilder("님의 매력포인트를 높여주는 효과가 있습니다. ");
    	((TextView)layout.findViewById(R.id.text_explain)).append(sp);
    	sp = new SpannableStringBuilder(tournamentMakerID);
    	sp.setSpan(new ForegroundColorSpan(getResources().getColor(R.color.textOrange)), 0, sp.length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
    	((TextView)layout.findViewById(R.id.text_explain)).append(sp);
    	sp = new SpannableStringBuilder("님의 매력에 어울리는 선물을 해보세요!");
    	((TextView)layout.findViewById(R.id.text_explain)).append(sp);
    	
    	sp = new SpannableStringBuilder("80%의 클로버");
    	sp.setSpan(new ForegroundColorSpan(getResources().getColor(R.color.textGreen)), 0, sp.length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
    	((TextView)layout.findViewById(R.id.text_explain_02)).append(sp);
    	sp = new SpannableStringBuilder("를 되돌려받을 수 있습니다.");
    	((TextView)layout.findViewById(R.id.text_explain_02)).append(sp);
    	
    	RelativeLayout okButton = (RelativeLayout)layout.findViewById(R.id.btn_ok);
    	okButton.setOnClickListener(new OnClickListener() {
    		//구매 버튼 처리
    		@Override
    		public void onClick(View v) {
				customDialogInstance.dismiss();
    		}
    	});
    	
    	builder = new AlertDialog.Builder(this);
    	builder.setView(layout);
    	alertDialog = builder.create();
    	
    	return alertDialog;
    }
    
    private void giftLayoutListReset() {
    	for (int i=0;i < giftLayoutList.size();i++) {
    		giftLayoutList.get(i).setBackgroundResource(R.drawable.bg_gift_list_unselect);
    	}
    	selectedGiftLayout.setBackgroundResource(R.drawable.bg_gift_list_select);
    }
    
	public void viewToast(int gravity, int xOffset, int yOffset, String message) {
		Toast toast = Toast.makeText(this, message, Toast.LENGTH_SHORT);
		toast.setGravity(gravity, xOffset, yOffset);
		toast.show();
	}
	
	private void hideKeyboard() {
		EditText editTextAnswer = (EditText) findViewById(R.id.editTextAnswer);
    	InputMethodManager mgr = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
    	mgr.hideSoftInputFromWindow(editTextAnswer.getWindowToken(), 0);
	}
	
}
